<template>
  <div class="login" :style="backImg">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">{{sysTitle}}</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="账号/手机"
        >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img"/>
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
    <el-dialog :title="title" :visible.sync="openPhone" width="400px" style="top:20%" :before-close="handleClose" append-to-body v-dialogDrag :close-on-click-modal="false">
      <el-form ref="formCode" :model="formCode" :rules="codeRules" @submit.native.prevent>
        <div class="form_text">验证注册手机号：{{phoneNumber}}</div>
        <el-form-item prop="code">
          <el-input v-model="formCode.code" placeholder="请输入验证码" style="width:60%" @keyup.enter.native="submitCode"/>
          <el-button
            type="primary"
            @click="getMobileCodeByLogin(realPhoneNumber)"
            :disabled="show"
            style="width:35%;margin-left:5%"
          >{{ codeText }}</el-button>
        </el-form-item>
      </el-form>
      <el-button class="form_submit" type="primary" @click="submitCode">确 认</el-button>
    </el-dialog>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2025 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { getPhone, checkSms, sendSms, sendSmsByPhone, setValidPhoneEnabled, setValidPhoneCode } from "@/api/loginPlus";
import { getToken, removeToken } from '@/utils/auth'
import backImg from "@/assets/images/login-background.jpg";
export default {
  name: "Login",
  data() {
    return {
      title: process.env.VUE_APP_TITLE,
      validPhoneEnabled: false,
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
       codeRules: {
        code: [{ required: true, trigger: "blur", message: "验证码不能为空" }]
      },
      TELRGE:/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/ ,
      sysTitle: '',
      backImg: `background-image: url('${backImg}');`,
      formCode: {},
      openPhone: false,
      show: false,
      phoneNumber: "",
      realPhoneNumber: "",
      codeText: "获取验证码",
      title: "验证码登录",
      captchaType: "",
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.getCode()
    this.getCookie()
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        // 获取背景图
        if(res.backImg === undefined || res.backImg.trim() === "" ) {
          this.backImg = `background-image: url('${backImg}');`
        } else {
          this.backImg ='background-image: url("'+ res.backImg + '");'
        }
        // 获取标题
        if(res.title === undefined || res.title.trim() === "" ) {
          this.sysTitle = process.env.VUE_APP_TITLE
        } else {
          this.sysTitle = res.title
          window.document.title = res.title
        }
        Cookies.set("sysTitle", this.sysTitle)
        this.captchaType = res.captchaType
        this.validPhoneEnabled = res.validPhoneEnabled === undefined ? false : res.validPhoneEnabled
        setValidPhoneEnabled(this.validPhoneEnabled + '')
        if (this.validPhoneEnabled === true) {
          setValidPhoneCode('false')
        }
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img
          this.loginForm.uuid = res.uuid
        }
      })
    },
    getCookie() {
      const username = Cookies.get("username")
      const password = Cookies.get("password")
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      }
    },
    handleLogin() {
      // 有token后再次点击登陆清除token重新获取
      if(getToken()) {
         removeToken();
      };
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 })
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 })
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 })
          } else {
            Cookies.remove("username")
            Cookies.remove("password")
            Cookies.remove('rememberMe')
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            if(this.validPhoneEnabled === true) {
                setValidPhoneCode('false')
                this.clearTimer()
                this.loading = false
                this.openPhone = true
                getPhone().then(res => {
                  this.realPhoneNumber = res.phone
                  this.phoneNumber = res.phone.substr(0,3)+'****'+res.phone.substr(7)
                });
                return
            } else {
              this.$router.push({ path: this.redirect || "/" }).catch(()=>{})
            }
          }).catch(() => {
            this.loading = false
            if (this.captchaEnabled) {
              this.getCode()
            }
          })
        }
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
     // 验证码倒计时
    getMobileCodeByForgetPwd(phoneNumber) {
        if(!this.TELRGE.test(phoneNumber)) {
           this.msgSuccess("手机号格式错误！");
           return;
        }
        sendSmsByPhone(phoneNumber).then(res => {
         if(res.code == 200) {
            this.msgSuccess(res.msg);
         } else {
           this.msgSuccess(res.msg);
         }
       });
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.show = true;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
            this.codeText = `${this.count}s后重新获取`;
          } else {
            this.clearTimer();
          }
        }, 1000);
      }
    },
     // 验证码倒计时
    getMobileCodeByLogin(phoneNumber) {
       sendSms(phoneNumber).then(res => {
         if(res.code == 200) {
            this.msgSuccess(res.msg);
         } else {
           this.msgSuccess(res.msg);
         }
       });
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.show = true;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
            this.codeText = `${this.count}s后重新获取`;
          } else {
            this.clearTimer();
          }
        }, 1000);
      }
    },
    // 验证码提交
    submitCode() {
       this.$refs.formCode.validate(valid => {
        if (valid) {
          checkSms(this.realPhoneNumber, this.formCode.code).then(res => {
            if(res.isOk) {
               // 手机验证时需要存入
                setValidPhoneCode('true');
                this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
            } else {
              this.msgError("验证码错误");
            }
         });
        }
      });
    },
    // 清除倒计时
    clearTimer() {
      this.show = false;
      this.codeText = "获取验证码";
      clearInterval(this.timer);
      this.timer = null;
    },
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  z-index: 1;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
.form_text {
  width: 100%;
  height: 30px;
  font-size: 16px;
}
.form_button {
  width: 40%;
  margin: 0 auto;
}
.form_submit {
  width: 100%;
}
</style>
